/*
    /login => 登录页面
    /register = > 注册页面
*/

const http = require('http')
const qs = require('querystring')
const fs = require('fs')
const {
    stringify
} = require('querystring')
let personms = JSON.parse(fs.readFileSync('persons.json', 'utf8'));
const server = http.createServer()
server.listen(3000)


server.on('request', (req, res) => {

    res.writeHead(200, {
        'Content-type': 'text/html;charset=utf8'
    })
    // res.end( req.url )
    // res.end( req.url.startsWith( '/login' ) )
    if (req.url.startsWith('/login')) {
        //req.url :  /login?username=aaa&password=bbb
        //先 ? 分割
        let a = {}
        a = qs.parse(req.url.split('?')[1])
        console.log(a);
        // 再用 querystring.parse() 转换成对象 
        if (personms.some((item) => {
            // return item;
            return item.username == a.username && item.password == a.password;
        })) {
            res.end('登陆成功')
        } else {
            res.end('用户名或者密码错误')
        }

    } else if (req.url.startsWith('/register')) {
        let a = {}
        a = qs.parse(req.url.split('?')[1])
        if (personms.find((item) => {
            return item.username == a.username;
        })) {
            res.end('注册失败已有账户名');
        } else {
            personms.push(a);
            fs.writeFileSync('persons.json', JSON.stringify(personms))
            res.end('注册成功');
        }
    }


})